package com.qf.xiaomi.web.base;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 公共的servlet
 * 1. 接收所有的请求
 * 2. 根据参数分发请求
 *
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // login, register, logout
        String method = req.getParameter("method");
        System.out.println("method: "+method);
        //this: userServlet
        Class clazz = this.getClass();
        try {
            //通过反射的方式动态获取 对应的方法
            Method meth
                    = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);

            //通过反射的方式运行方法
            /**
             * 参数1： 真实对象（要运行哪个对象中的方法）
             * 参数2： 实参
             */
            Object result = meth.invoke(this, req, resp);
            //如果 方法返回值是void， result 为null
            if(result != null){
                String res = (String) result;
                //根据冒号切割
                String[] arr = res.split(":");
                //如果 数组的第一个元素为 redirect ， 则为重定向
                if("redirect".equalsIgnoreCase(arr[0])) {
                    resp.sendRedirect(arr[1]);
                } else {
                    req.getRequestDispatcher(arr[1]).forward(req, resp);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
